//
//  WHUserManager.m
//  BinFengExpressOwner
//
//  Created by 邓伟浩 on 2018/10/23.
//  Copyright © 2018年 BinFeng. All rights reserved.
//

#import "WHUserManager.h"
#import "NSString+WH3DES.h"

#import "JPUSHService.h"

@interface WHUserManager ()

@property (nonatomic, strong) NSURLSessionDataTask *accountLoginTask;

@end

@implementation WHUserManager

SINGLETON_FOR_CLASS(WHUserManager);

- (void)cancelRequest {
    if (_accountLoginTask) {
        [_accountLoginTask cancel];
        _accountLoginTask = nil;
    }
}

- (void)defaultSetting {
    BOOL isRuned = [kUserDefaults boolForKey:@"isRuned"]; //0
    if (!isRuned) {
        DLog(@"第一次运行程序");
        [kUserDefaults setBool:YES forKey:@"isRuned"];
        
        [kUserDefaults setBool:YES forKey:InVoice];
        [kUserDefaults setBool:YES forKey:OutVoice];
        [kUserDefaults synchronize];
        
    }
}

- (instancetype)init {
    if (self = [super init]) {
        [kNotificationCenter addObserver:self
                                selector:@selector(userInfoChange:)
                                    name:KUserInfoChange
                                  object:nil];
        
    }
    return self;
}

- (void)userInfoChange:(NSNotification *)notification {

    [self LoadDetailUserInfoWithCompletion:^(BOOL success, NSString *des) {
        if (success) {
            DLog(@"重新加载用户信息成功");
        }
        
    }];
}

#pragma mark —————— 登录接口 ——————

/** 账号登录 */
- (void)doAccountLoginWithPhoneNumber:(NSString *)phoneNumber password:(NSString *)password completion:(loginBlock)completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_userLogin);
    NSString *encryptStr = [NSString encryptUseDES3:password key:DES3Key];
    NSString *registrationId = [JPUSHService registrationID];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          phoneNumber, @"userCell",
                          encryptStr, @"passWord",
                          registrationId?:@"iOSSimulator", @"registrationId",
                          @"1", @"system",
                          nil];
    
    _accountLoginTask = [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"登陆信息: %@", responseObject);
        [self loginStatus:responseObject completion:completion];
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO, @"网络异常!");
        }
    }];
}

#pragma mark ————— 登录结果处理 —————
- (void)loginStatus:(id)responseObject completion:(loginBlock)completion {
    if (ValidDict(responseObject)) {
        NSNumber *errorCode = responseObject[@"errcode"];
        NSString *errorMsg = responseObject[@"errmsg"];
        
        if (errorCode.intValue == 0) {
            NSDictionary *userModel = responseObject[@"retobj"];
            WHDetailUserInfo *detailUserInfo = [WHDetailUserInfo modelWithDictionary:userModel];
            self.detailUserInfo = detailUserInfo;
            
            self.isLogined = YES;
            [self saveUserInfo];
            
            [[UIApplication sharedApplication] registerForRemoteNotifications];
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
            
            // 注册别名
            [JPUSHService setAlias:NSStringFormat(@"Seller%d", self.detailUserInfo.userId) completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                
                DLog(@"iAlias = %@", iAlias);
            } seq:100];
            
            [self LoadDetailUserInfoWithCompletion:nil];
            
            completion(YES, errorMsg);
        } else {
            self.isLogined = NO;
            completion(NO, errorMsg);
        }
    }
}

#pragma mark ————— 储存用户信息 —————
- (void)saveUserInfo {
    if (self.detailUserInfo) {
        YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
        NSDictionary *dic = [self.detailUserInfo modelToJSONObject];
        [cache setObject:dic forKey:KUserModelCache];
    }
    
}

#pragma mark ————— 加载缓存的用户信息 —————
- (BOOL)loadUserInfo {
    YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
    NSDictionary *userDic = (NSDictionary *)[cache objectForKey:KUserModelCache];
    if (userDic) {
        self.detailUserInfo = [WHDetailUserInfo modelWithJSON:userDic];
        DLog(@"加载缓存用户信息成功!");
        [self LoadDetailUserInfoWithCompletion:^(BOOL success, NSString *des) {
            if (success) {
                DLog(@"用户详细信息加载完成!");
            }
            
        }];
        return YES;
    }
    return NO;
}

- (BOOL)isLogined {
    if (!_isLogined) {
        KPostNotification(KNotificationLoginStateChange, @NO);
    }
    
    return _isLogined;
}

#pragma mark ————— 加载详细用户信息 —————

- (void)LoadDetailUserInfoWithCompletion:(loginBlock)completion {
    
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_finduser);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@(userManager.detailUserInfo.userId), @"userId", userManager.detailUserInfo.token, @"token", nil];
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"用户详细信息: %@", responseObject);
        if (ValidDict(responseObject)) {
            
            NSNumber *errorCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            
            if (errorCode.intValue == 0) {
                NSDictionary *detailUserModel = responseObject[@"retobj"];
                WHDetailUserInfo *detailUseInfo  = [WHDetailUserInfo modelWithDictionary:detailUserModel];
                if ([detailUseInfo.token isEqualToString:self.detailUserInfo.token]) {
                    if (completion) {
                        completion(YES, nil);
                    }
                    self.isLogined = YES;
                    self.detailUserInfo = detailUseInfo;
                    
                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                    KPostNotification(KUserDetailInfoChange, nil);
                } else {
                    self.isLogined = NO;
                    [self logout:nil];
                    if (completion) {
                        completion(NO, errorMsg);
                    }
                }
                
            } else {
                [WHView showHudMsgAtCenter:@"登陆失效!"];
                self.isLogined = NO;
                
                [self logout:nil];
                if (completion) {
                    completion(NO, errorMsg);
                }
                DLog(@"loadDetailInfoError: %@", errorMsg);
                
            }
            
        }
        
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO, @"网络异常!");
        }
    }];
}

#pragma mark ————— 退出登录 —————
- (void)logout:(loginBlock)completion {
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        DLog(@"deleteIAlias = %@", iAlias);
    } seq:101];
    [JPUSHService resetBadge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // 清空角标
    [[UIApplication sharedApplication] unregisterForRemoteNotifications]; // 关闭接收通知
    self.detailUserInfo = nil;
    self.isLogined = NO;
    
    DLog(@"退出登录");
    //移除缓存
    YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
    [cache removeObjectForKey:KUserModelCache];
    
    KPostNotification(KUserDetailInfoChange, nil);
    KPostNotification(KNotificationLoginStateChange, @NO);
    
    if (completion) {
        completion(YES, nil);
    }
}

@end
